package com.fushenlan.epidemicControl.controller;

/**
 * @author zhulei
 * @title: NucleicDetectionController
 * @projectName 核酸检测相关
 * @description:
 * @date 2022/4/25
 */

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fushenlan.commons.GeneralResponse;
import com.fushenlan.enums.CommonCodeEnum;
import com.fushenlan.epidemicControl.config.JwtUtil;
import com.fushenlan.epidemicControl.dto.DetectionPersonalInfoDetailsRespDTO;
import com.fushenlan.epidemicControl.dto.DetectionPersonalInfoRespDTO;
import com.fushenlan.epidemicControl.dto.NucleinDetectionApplyRecordRespDTO;
import com.fushenlan.epidemicControl.dto.NucleinDetectionResultRespDTO;
import com.fushenlan.epidemicControl.dto.request.NucleinDetectionApplyRecordReqDTO;
import com.fushenlan.epidemicControl.service.NucleinDetectionApplyRecordService;
import com.fushenlan.helper.ListPageHelper;
import com.fushenlan.po.PageInfoVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "pc核酸检测")
@Slf4j
@RestController
@RequestMapping("/pcNucleic")
public class NucleicDetectionController {

    @Autowired
    private NucleinDetectionApplyRecordService nucleinDetectionApplyRecordService;

    /**
     * 核酸检测申请记录查询
     *
     * @param startDate,endDate
     * @return
     */
    @GetMapping("/queryNucleinDetectionApplyRecord")
    public GeneralResponse<PageInfoVo> queryNucleinDetectionApplyRecord(@RequestParam("startDate") String startDate,
                                                            @RequestParam("endDate") String endDate,
                                                            @RequestParam("pageSize") Integer pageSize,
                                                            @RequestParam("pageNo") Integer pageNo) {
        log.info("查询核酸申请记录：queryNucleinDetectionApplyRecord入参：开始日期:{}，结束日期:{}", startDate, endDate);
        PageHelper.startPage(pageNo, pageSize);
        List<NucleinDetectionApplyRecordRespDTO> response = nucleinDetectionApplyRecordService.queryNucleinDetectionApplyRecord(startDate, endDate);
        PageInfo<NucleinDetectionApplyRecordRespDTO> pageInfo = new PageInfo<>(response);
        PageInfoVo pageDateInfoVo = ListPageHelper.StartPage(pageInfo);
        log.info("查询核酸申请记录：queryNucleinDetectionApplyRecord出参：{}", response);
        return GeneralResponse.success(pageDateInfoVo);
    }

    /**
     * 核酸检测申请-新增检测
     *
     * @param req
     * @return GeneralResponse
     */
    @PostMapping("/insertNucleinDetectionApplyRecord")
    @ApiOperation(value = "核酸检测申请-新增检测", notes = "核酸检测申请-新增检测")
    public GeneralResponse insertNucleinDetectionApplyRecord(@RequestBody NucleinDetectionApplyRecordReqDTO req) {
        return nucleinDetectionApplyRecordService.insertNucleinDetectionApplyRecord(req);

    }
    /**
     * 查看核酸检测申请记录
     *
     * @param
     * @return
     */
    @GetMapping("/LookNucleinDetectionApplyRecord")
    public GeneralResponse<NucleinDetectionApplyRecordRespDTO> LookNucleinDetectionApplyRecord(@RequestParam("detectionId") Long detectionId) {
        log.info("查看核酸申请记录：LookNucleinDetectionApplyRecord入参：检测id:{}", detectionId);
        GeneralResponse<NucleinDetectionApplyRecordRespDTO> response = nucleinDetectionApplyRecordService.LookNucleinDetectionApplyRecord(detectionId);
        log.info("查询核酸申请记录：LookNucleinDetectionApplyRecord出参：{}", response);
        return response;
    }

    /**
     * 下载导入核酸检测人员列表信息列表模板excel
     *
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/downloadNucleinDetectionApplyRecordModel", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "下载核酸检测人员列表模板excel列表", notes = "下载核酸检测人员列表模板excel列表")
    public GeneralResponse downloadNucleinDetectionApplyRecordModel(HttpServletResponse response) throws IOException {
        List<DetectionPersonalInfoRespDTO> detectionPersonalInfoRespDTOS = new ArrayList<>();
        DetectionPersonalInfoRespDTO detectionPersonalInfoRespDTO = new DetectionPersonalInfoRespDTO();
        detectionPersonalInfoRespDTO.setAddress("龙沟新苑22号888");
        detectionPersonalInfoRespDTO.setUserName("例如:zzz");
        detectionPersonalInfoRespDTO.setIdentifyType(1);
        detectionPersonalInfoRespDTO.setIdentifyNo("110101198803074019");
        detectionPersonalInfoRespDTO.setPhoneNumber("11010119880");
        detectionPersonalInfoRespDTO.setIfDetection(1);

        detectionPersonalInfoRespDTOS.add(detectionPersonalInfoRespDTO);
        // 导出数据，数据，数据类型，响应对象文件名称
        nucleinDetectionApplyRecordService.downloadNucleinDetectionApplyRecordModel(detectionPersonalInfoRespDTOS, response);
        return GeneralResponse.success();
    }

    /**
     * 导入核酸检测人员列表列表数据
     *
     * @param
     * @param response
     * @throws IOException
     */
    @PostMapping(value = "/uploadNucleinDetectionApplyRecordList")
    @ApiOperation(value = "导入核酸检测人员列表列表数据")
    public GeneralResponse<List<DetectionPersonalInfoRespDTO>> uploadNucleinDetectionApplyRecordList(@ApiParam(value = "文件对象") @RequestParam("file") MultipartFile multipartFile,  HttpServletResponse response) throws IOException {

        GeneralResponse<List<DetectionPersonalInfoRespDTO>> resp = new GeneralResponse<>();

        // 导出数据，数据，数据类型，响应对象文件名称
        try {
            resp = nucleinDetectionApplyRecordService.uploadNucleinDetectionApplyRecordList( multipartFile, response);
        } catch (Exception e) {
            log.error("读取文件异常====>{}", e);
        }
        return resp;
    }

    /**
     * 核酸检测结果查询
     *
     * @param startDate,endDate
     * @return
     */
    @GetMapping("/queryNucleinDetectionResult")
    @ApiOperation(value = "核酸检测结果查询")
    public GeneralResponse<PageInfo<NucleinDetectionResultRespDTO>> queryNucleinDetectionResult(@RequestParam("startDate") String startDate,
                                                                        @RequestParam("endDate") String endDate,
                                                                        @RequestParam("pageSize") Integer pageSize,
                                                                        @RequestParam("pageNo") Integer pageNo) {
        log.info("查询核酸检测结果：queryNucleinDetectionResult入参：开始日期:{}，结束日期:{} 分页大小：{}，页数{}", startDate, endDate,pageSize,pageNo);

        List<NucleinDetectionResultRespDTO> list = nucleinDetectionApplyRecordService.queryNucleinDetectionResult(startDate, endDate,pageSize,pageNo);
        int total = list.size();
        if (total > pageSize) {
            int toIndex = pageSize * pageNo;
            if (toIndex > total) {
                toIndex = total;
            }
            list = list.subList(pageSize * (pageNo - 1), toIndex);
        }
        Page<NucleinDetectionResultRespDTO> page = new Page<>(pageNo, pageSize);
        page.addAll(list);
        page.setPages((total + pageSize - 1) / pageSize);
        page.setTotal(total);

        PageInfo<NucleinDetectionResultRespDTO> pageInfo = new PageInfo<>(page);
        log.info("查询核酸检测结果：queryNucleinDetectionResult出参：{}", pageInfo);
        return GeneralResponse.success(pageInfo);
    }

    /**
     * 核酸检测结果详情查询
     *
     * @param
     * @return
     */
    @GetMapping("/queryNucleinDetectionResultDetails")
    @ApiOperation(value = "核酸检测结果详情查询")
    public GeneralResponse<IPage<DetectionPersonalInfoRespDTO>> queryNucleinDetectionResultDetails(@RequestParam(required = false,value = "community") Long community,
                                                                                                   @RequestParam(required = false, value = "name") String name,
                                                                                                   @RequestParam(required = false, value = "detectionResult") Integer detectionResult,
                                                                                                   @RequestParam(required = false, value = "userStatus") Integer userStatus,
                                                                                                   @RequestParam(required = false, value = "ifDetection") Integer ifDetection,
                                                                                                   @RequestParam(required = false, value = "detectionId") Long detectionId,
                                                                                                   @RequestParam("pageSize") Integer pageSize,
                                                                                                   @RequestParam("pageNo") Integer pageNo) {
        log.info("查询核酸检测结果详情：queryNucleinDetectionResultDetails入参:{} ", community,name,detectionResult,userStatus,ifDetection,detectionId,pageSize,pageNo);
        GeneralResponse<IPage<DetectionPersonalInfoRespDTO>> response = nucleinDetectionApplyRecordService.queryNucleinDetectionResultDetails(community,name,detectionResult,userStatus,ifDetection,detectionId, pageSize,pageNo);
        log.info("查询核酸检测结果详情：queryNucleinDetectionResultDetails出参：{}", response);
        return response;
    }

    /**
     * 导出核酸检测详情列表
     *
     * @param detectionId 检测id
     * @param response
     * @throws IOException
     */
    @GetMapping(value = "/exportNucleinDetectionResultDetails")
    @ApiOperation(value = "导出核酸检测详情列表数据至excel中")
    public GeneralResponse exportNucleinDetectionResultDetails(@RequestParam(required = false,value = "community") Long community,
                                                               @RequestParam(required = false, value = "name") String name,
                                                               @RequestParam(required = false, value = "detectionResult") Integer detectionResult,
                                                               @RequestParam(required = false, value = "userStatus") Integer userStatus,
                                                               @RequestParam(required = false, value = "ifDetection") Integer ifDetection,
                                                               @RequestParam(required = false, value = "detectionId") Long detectionId,
                                                               HttpServletResponse response) throws IOException {
        // 导出数据，数据，数据类型，响应对象文件名称
        try {
            return nucleinDetectionApplyRecordService.exportNucleinDetectionResultDetails(community,name,detectionResult,userStatus,ifDetection,detectionId, response);
        }catch (Exception e){
            log.error(e.getMessage());
            return GeneralResponse.fail();
        }
    }
    /**
     * 下载导入核酸检测结果详情人员模板excel
     *
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/downloadNucleinDetectionResultDetails", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "下载导入核酸检测结果详情人员模板excel", notes = "下载导入核酸检测结果详情人员模板excel")
    @ResponseBody
    public void downloadNucleinDetectionResultDetails(HttpServletResponse response) throws IOException {
        List<DetectionPersonalInfoDetailsRespDTO> detectionPersonalInfoRespDTOS = new ArrayList<>();
        DetectionPersonalInfoDetailsRespDTO detectionPersonalInfoRespDTO = new DetectionPersonalInfoDetailsRespDTO();
        //导入字段：地址、姓名、证件类型、证件号码、手机、是否已检测
        detectionPersonalInfoRespDTO.setAddress("龙沟新苑28号902");
        detectionPersonalInfoRespDTO.setUserName("例如:zzz");
        detectionPersonalInfoRespDTO.setIdentifyType(1);
        detectionPersonalInfoRespDTO.setIdentifyNo("110101198803074020");
        detectionPersonalInfoRespDTO.setPhoneNumber("1511234129058");
        detectionPersonalInfoRespDTO.setIfDetection(1);
        detectionPersonalInfoRespDTOS.add(detectionPersonalInfoRespDTO);
        // 导出数据，数据，数据类型，响应对象文件名称
        nucleinDetectionApplyRecordService.downloadNucleinDetectionResultDetails(detectionPersonalInfoRespDTOS, response);
    }
    /**
     * 导入核酸检测结果详情人员
     *
     * @param
     * @param response
     * @throws IOException
     */
    @PostMapping(value = "/uploadNucleinDetectionResultDetails")
    @ApiOperation(value = "导入核酸检测结果详情人员")
    public GeneralResponse<List<DetectionPersonalInfoRespDTO>> uploadNucleinDetectionResultDetails(@ApiParam(value = "文件对象") @RequestParam("file") MultipartFile multipartFile,
                                                                                                   @RequestParam("detectionId") Long detectionId,
                                                                                                   HttpServletResponse response) throws IOException {

        GeneralResponse<List<DetectionPersonalInfoRespDTO>> resp = new GeneralResponse<>();
        // 导出数据，数据，数据类型，响应对象文件名称
        try {
            resp = nucleinDetectionApplyRecordService.uploadNucleinDetectionResultDetails(multipartFile,detectionId,response);
        } catch (Exception e) {
            log.error("读取文件异常====>{}", e);
        }
        return resp;
    }

    /**
     * 密接查询
     * @param userId      用户id
     * @param detectionId 核酸申请记录id
     * @return
     */
    @GetMapping("/querycloseContactInfo")
    public GeneralResponse<List<DetectionPersonalInfoRespDTO>> querycloseContactInfo(@RequestParam("userId") Long userId,
                                                                                @RequestParam(required = false, value = "detectionId") Long detectionId) {
        try {
            return nucleinDetectionApplyRecordService.querycloseContactInfo(userId, detectionId);
        } catch (Exception e) {
            log.error(e.getMessage());
            return GeneralResponse.fail();
        }
    }

    /**
     * 通知登记接口
     * 修改 申请记录表 `if_input_results` 是否开始录入结果 0-否 1-是 ', 是
     * @param detectionId 核酸申请记录id
     * @return
     */
    @GetMapping("/noticeRegister")
    public GeneralResponse noticeRegister(@RequestParam(required = true, value = "detectionId") Long detectionId) {
        try {
            int record = nucleinDetectionApplyRecordService.noticeRegister(detectionId);
            if(record >0){
                return GeneralResponse.success();
            }else {
                return GeneralResponse.fail();
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return GeneralResponse.fail();
        }
    }

    /**
     * 修改检测结果
     *
     * @param userId 用户id
     * @return
     */
    @GetMapping("/updateDetectionResult")
    public GeneralResponse updateDetectionResult(@RequestParam("userId") Long userId,
                                                 @RequestParam("detectionId") Long detectionId,
                                                 @RequestParam("detectionResult") Integer detectionResult) {
        log.info("修改检测结果 Request userId->{},detectionId->{},detectionResult->{}", userId, detectionId,detectionResult);
        int result = nucleinDetectionApplyRecordService.updateDetectionResult(userId, detectionId, detectionResult);
        log.info("修改检测结果 Response personalInfoRespDTOS->{}", result);
        return GeneralResponse.success(result);
    }
}
